package com.yiquan.chat.controller;

import com.yiquan.chat.pojo.Converse;
import com.yiquan.chat.pojo.Message;
import com.yiquan.chat.service.ConverseService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author Tyrone
 * @date 2022/1/2 14:17
 */
@RestController
@RequestMapping("/converse")
@CrossOrigin
public class ConverseController {
    @Autowired
    private ConverseService converseService;

    /**
     * 增加会话
     *
     * @param userId
     * @param theUserId
     * @return
     */
    @PostMapping
    public Result addConverse(@RequestParam Long userId, @RequestParam Long theUserId) {
        Long success = converseService.addOrGetConverse(userId, theUserId);
        if (success != null)
            return new Result(true, StatusCode.OK, "会话添加成功",success);
        return new Result(false, StatusCode.ERROR, "会话添加失败",success);
    }

    /**
     * 获取当前用户的会话列表
     *
     * @param userId
     * @return
     */
    @GetMapping
    public Result getConverseList(@RequestParam Long userId) {
        List<Converse> converseList = converseService.getConverseList(userId);
        return new Result(true, StatusCode.OK, "会话列表获取成功", converseList);
    }

    /**
     * 获取当前会话最后一条信息
     *
     * @param userId
     * @param theUserId
     * @return
     */
    @GetMapping("/getLastMsgOfConverse")
    public Result getLastMsgOfConverse(@RequestParam Long  userId, @RequestParam Long theUserId) {
        Message lastMsg = converseService.getLastMsgOfConverse(Long.valueOf(userId), Long.valueOf(theUserId));
        return new Result(true, StatusCode.OK, "查询成功", lastMsg);
    }

    /**
     * 根据会话id删除会话
     * @param converseId
     * @return
     */
    @DeleteMapping()
    public Result deleteConverseByConverseId(@RequestParam Long converseId){
        converseService.deleteByConverseId(Long.valueOf(converseId));
        return new Result(true, StatusCode.OK, "删除成功");
    }

    @PostMapping("/backend/search/{page}/{size}")
    public Result backendSearch(@RequestBody Map searchMap,@PathVariable("page")int page,@PathVariable("size") int size){
        Page<Converse> search = converseService.findSearch(searchMap, page, size);
        return new Result(new PageResult<>(search.getTotalElements(),search.getContent()));
    }

    @DeleteMapping("/batchDelete")
    public Result batchDelete(@RequestParam List<Long> converseList){
        converseService.batchDelete(converseList);
        return new Result(true, StatusCode.OK, "删除成功");
    }



}
